package com.service.contractor;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.dao.contractor.VisaDao;
import com.dao.supply.InfoMapper;
import com.dao.sys.SysUserMapper;
import com.enums.FactoryEnum;
import com.enums.WorkFlowIdModel;
import com.model.contractor.VisaModel;
import com.model.external.oa.OaWorkFlowResult;
import com.model.supply.SupplyUserModel;
import com.model.sys.SysUser;
import com.service.external.oa.CreateSPVisaService;
import com.service.external.oa.CreateXYVisaService;
import com.service.external.oa.GetWFStatusService;
import com.service.purchase.CommonService;

import cn.com.weaver.services.webservices.WorkflowServiceStub.ArrayOfWorkflowRequestLog;
import cn.com.weaver.services.webservices.WorkflowServiceStub.ArrayOfWorkflowRequestTableField;
import cn.com.weaver.services.webservices.WorkflowServiceStub.GetWorkflowRequestResponse;
import cn.com.weaver.services.webservices.WorkflowServiceStub.WorkflowMainTableInfo;
import cn.com.weaver.services.webservices.WorkflowServiceStub.WorkflowRequestLog;
import cn.com.weaver.services.webservices.WorkflowServiceStub.WorkflowRequestTableField;
import cn.com.weaver.services.webservices.WorkflowServiceStub.WorkflowRequestTableRecord;

import com.common.model.Global;
import com.common.spring.SpringMvcUtils;

@Service
public class VisaService {
	static final Logger logger = LoggerFactory.getLogger(VisaService.class);

	@Autowired
	VisaDao visaDao;
	@Autowired
	CommonService commonService;
	@Autowired
	SysUserMapper sysUserMapper;
	@Autowired
	InfoMapper infoMapper;
	@Autowired
	CreateXYVisaService createXYVisaService;
	@Autowired
	CreateSPVisaService createSPVisaService;
	@Autowired
	GetWFStatusService wfStatusService;
	@Autowired
	GetWFStatusService getWFStatusService;

	/**
	 * 列表查询
	 *
	 * @param queryMap
	 * @return
	 */
	public HttpResult selectList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				queryMap.put("visDockId", sysUser.getUserid());
			}
		}
		List<VisaModel> list = visaDao.selectList(queryMap);
		int count = visaDao.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	public HttpResult selectListXY(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		SupplyUserModel sysUser = SpringMvcUtils.getSupplyUser();
		queryMap.put("createId", sysUser.getUserId());
		List<VisaModel> list = visaDao.selectList(queryMap);
		int count = visaDao.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	public HttpResult selectListSP(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		SupplyUserModel sysUser = SpringMvcUtils.getSupplyUser();
		queryMap.put("createId", sysUser.getUserId());
		List<VisaModel> list = visaDao.selectList(queryMap);
		int count = visaDao.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	/**
	 * 详情
	 * 
	 * @param
	 * @return
	 */
	public HttpResult selectInfor(String visId) {
		HttpResult httpResult = new HttpResult();
		VisaModel visaModel = visaDao.load(visId);
		httpResult.setData(visaModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 保存
	 *
	 * @param
	 * @return
	 */
	public HttpResult saveXY(VisaModel visaModel) {
		if (visaModel == null) {
			return HttpResult.error("参数不能为空");
		}
		SupplyUserModel supplyUserModel = SpringMvcUtils.getSupplyUser();
		HttpResult httpResult = new HttpResult();
		int result = 0;
		visaModel.setVisConName(supplyUserModel.getInforName());
		visaModel.setVisFactoryCode(FactoryEnum.xy.getValue());
		visaModel.setVisFactoryName(FactoryEnum.xy.getName());

		if (!StringUtils.isNotNull(visaModel.getVisId())) {
			visaModel.setVisId(UUID.randomUUID().toString());
			visaModel.setVisCode(commonService.createCode("con_visa", "vis_code"));
			result = visaDao.insert(visaModel);
		} else {
			result = visaDao.update(visaModel);
		}
		if (result > 0) {
			httpResult.setMsg(visaModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(visaModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(visaModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	public HttpResult saveSP(VisaModel visaModel) {
		if (visaModel == null) {
			return HttpResult.error("参数不能为空");
		}
		SupplyUserModel supplyUserModel = SpringMvcUtils.getSupplyUser();
		HttpResult httpResult = new HttpResult();
		int result = 0;
		visaModel.setVisConName(supplyUserModel.getInforName());
		visaModel.setVisFactoryCode(FactoryEnum.sp.getValue());
		visaModel.setVisFactoryName(FactoryEnum.sp.getName());

		if (!StringUtils.isNotNull(visaModel.getVisId())) {
			visaModel.setVisId(UUID.randomUUID().toString());
			visaModel.setVisCode(commonService.createCode("con_visa", "vis_code"));
			result = visaDao.insert(visaModel);
		} else {
			result = visaDao.update(visaModel);
		}
		if (result > 0) {
			httpResult.setMsg(visaModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(visaModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(visaModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	public HttpResult back(String id) {
		HttpResult httpResult = new HttpResult();

		if (StringUtils.isNullOrEmpty(id)) {
			return HttpResult.error("参数为空");
		}
		int result = 0;
		VisaModel visaModel = visaDao.load(id);
		if (StringUtils.isNotNull(visaModel.getOaFlowId())) {
			// oa退回才可撤回
			HttpResult oaHttpResult = wfStatusService.getWorkflowRequestLogs(visaModel.getVisDockHi(),
					WorkFlowIdModel.saleContractString, visaModel.getOaFlowId());
			if (oaHttpResult.getCode() != HttpStatus.SUCCESS_CODE) {
				return oaHttpResult;
			}
		}
		visaModel.setStatus(Global.NO + "");
		result = visaDao.update(visaModel);
		if (result > 0) {
			httpResult.setMsg("撤回成功!");
		} else {
			httpResult.setMsg("撤回失败!");
		}
		return httpResult;
	}

	public HttpResult printXY(String id) {
		if (StringUtils.isNullOrEmpty(id)) {
			return HttpResult.error("参数为空");
		}

		int result = 0;
		VisaModel visaModel = visaDao.load(id);
		if (visaModel.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("数据未提交！");
		}
		if (visaModel.getStatus().equals(Global.NUMERICAL_TWO + "")) {
			return HttpResult.ok();
		}
		if (StringUtils.isNotNull(visaModel.getOaFlowId())) {
			// oa状态
//			HttpResult oaHttpResult = getWFStatusService.getWFStatus(visaModel.getOaFlowId(), visaModel.getVisDockHi());
//			if (oaHttpResult.getCode() != HttpStatus.SUCCESS_CODE) {
//				return HttpResult.error("oa流程(" + visaModel.getOaFlowId() + ")未审批结束！");
//			}
			// 签字意见
			HttpResult statusHttpResult = getWFStatusService.getWorkflowRequest(visaModel.getOaFlowId(),
					visaModel.getVisDockHi());
			GetWorkflowRequestResponse response = (GetWorkflowRequestResponse) statusHttpResult.getData();
			WorkflowMainTableInfo mainTableInfo = response.getOut().getWorkflowMainTableInfo();
			WorkflowRequestTableRecord[] record = mainTableInfo.getRequestRecords().getWorkflowRequestTableRecord();
			ArrayOfWorkflowRequestTableField feFields = record[0].getWorkflowRequestTableFields();
			WorkflowRequestTableField[] tableField = feFields.getWorkflowRequestTableField();
			for (WorkflowRequestTableField workflowRequestTableField : tableField) {
				System.out.println("fieldname:" + workflowRequestTableField.getFieldName());
				System.out.println("fieldShowValue:" + workflowRequestTableField.getFieldShowValue());
				if (workflowRequestTableField.getFieldName().equals("XYBD03")) {
					visaModel.setDeptName(workflowRequestTableField.getFieldShowValue());// 部门
				} else if (workflowRequestTableField.getFieldName().equals("XYBD13")) {
					visaModel.setOaCode(workflowRequestTableField.getFieldShowValue());// 编号
				} else if (workflowRequestTableField.getFieldName().equals("xglc")) {
					visaModel.setVisRelativeFlow(workflowRequestTableField.getFieldShowValue());// 相关流程
				} else if (workflowRequestTableField.getFieldName().equals("XYBD17")) {
					visaModel.setVisConDate(workflowRequestTableField.getFieldShowValue());//
				} else if (workflowRequestTableField.getFieldName().equals("gcnr")) {
					visaModel.setVisDetail(workflowRequestTableField.getFieldShowValue());//
				}
			}

			ArrayOfWorkflowRequestLog requestLog = response.getOut().getWorkflowRequestLogs();
			WorkflowRequestLog[] logs = requestLog.getWorkflowRequestLog();
			String eycString = "", xcdbString = "";
			for (WorkflowRequestLog log : logs) {
				if (log.getNodeName().equals("审计部") && log.getOperateType().equals("批准")) {
					visaModel.setVisAudit(log.getOperatorName());
				} else if (log.getNodeName().equals("分管领导") && log.getOperateType().equals("批准")) {
					visaModel.setVisLeader(log.getOperatorName());
				} else if (log.getNodeName().equals("部门负责人") && log.getOperateType().equals("批准")) {
					visaModel.setVisDeptCharge(log.getOperatorName());
				} else if (log.getNodeName().equals("二元醇部门负责人") && log.getOperateType().equals("批准")) {
					eycString = "," + log.getOperatorName();
				} else if (log.getNodeName().equals("现场代表") && log.getOperateType().equals("提交")) {
					xcdbString = log.getOperatorName();
				} else {

				}
			}
			visaModel.setVisProxy(xcdbString + eycString);
		}

		if (StringUtils.isNotNull(visaModel.getVisAudit())) {
			visaModel.setStatus(Global.NUMERICAL_TWO + "");
			result = visaDao.update(visaModel);
		} else {
			result = visaDao.update(visaModel);
			return HttpResult.error("审批未结束！");
		}
		HttpResult httpResult = new HttpResult();
		if (result > 0) {
			httpResult.setMsg("成功!");
		} else {
			httpResult.setMsg("失败!");
		}
		return httpResult;
	}

	public HttpResult printSP(String id) {
		if (StringUtils.isNullOrEmpty(id)) {
			return HttpResult.error("参数为空");
		}

		int result = 0;
		VisaModel visaModel = visaDao.load(id);
		if (visaModel.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("数据未提交！");
		}
		if (visaModel.getStatus().equals(Global.NUMERICAL_TWO + "")) {
			return HttpResult.ok();
		}
		if (StringUtils.isNotNull(visaModel.getOaFlowId())) {
			// oa状态
//			HttpResult oaHttpResult = getWFStatusService.getWFStatus(visaModel.getOaFlowId(), visaModel.getVisDockHi());
//			if (oaHttpResult.getCode() != HttpStatus.SUCCESS_CODE) {
//				return HttpResult.error("oa流程(" + visaModel.getOaFlowId() + ")未审批结束！");
//			}
			// 签字意见
			HttpResult statusHttpResult = getWFStatusService.getWorkflowRequest(visaModel.getOaFlowId(),
					visaModel.getVisDockHi());
			GetWorkflowRequestResponse response = (GetWorkflowRequestResponse) statusHttpResult.getData();
			WorkflowMainTableInfo mainTableInfo = response.getOut().getWorkflowMainTableInfo();
			WorkflowRequestTableRecord[] record = mainTableInfo.getRequestRecords().getWorkflowRequestTableRecord();
			ArrayOfWorkflowRequestTableField feFields = record[0].getWorkflowRequestTableFields();
			WorkflowRequestTableField[] tableField = feFields.getWorkflowRequestTableField();
			for (WorkflowRequestTableField workflowRequestTableField : tableField) {
				System.out.println("fieldname:" + workflowRequestTableField.getFieldName());
				System.out.println("fieldShowValue:" + workflowRequestTableField.getFieldShowValue());

				if (workflowRequestTableField.getFieldName().equals("XYBD13")) {
					visaModel.setOaCode(workflowRequestTableField.getFieldShowValue());// 编号
				} else if (workflowRequestTableField.getFieldName().equals("xglc")) {
					visaModel.setVisRelativeFlow(workflowRequestTableField.getFieldShowValue());// 相关流程
				} else if (workflowRequestTableField.getFieldName().equals("XYBD17")) {
					visaModel.setVisConDate(workflowRequestTableField.getFieldShowValue());//
				} else if (workflowRequestTableField.getFieldName().equals("gcnr")) {
					visaModel.setVisDetail(workflowRequestTableField.getFieldShowValue());//
				}
			}

			ArrayOfWorkflowRequestLog requestLog = response.getOut().getWorkflowRequestLogs();
			WorkflowRequestLog[] logs = requestLog.getWorkflowRequestLog();
			String eycString = "", xcdbString = "";
			for (WorkflowRequestLog log : logs) {
				if (log.getNodeName().equals("审计部") && log.getOperateType().equals("批准")) {
					visaModel.setVisAudit(log.getOperatorName());
				} else if (log.getNodeName().equals("生产技术部分管领导") && log.getOperateType().equals("批准")) {
					visaModel.setVisLeader(log.getOperatorName());
				} else if (log.getNodeName().equals("生产技术部负责人") && log.getOperateType().equals("批准")) {
					visaModel.setVisDeptCharge(log.getOperatorName());
				} else if (log.getNodeName().equals("生产技术部经办人") && log.getOperateType().equals("批准")) {
					visaModel.setVisProxy(log.getOperatorName());
				} else if (log.getNodeName().equals("属地部门负责人") && log.getOperateType().equals("批准")) {
					eycString = "," + log.getOperatorName();
				} else if (log.getNodeName().equals("属地部门经办人") && log.getOperateType().equals("提交")) {
					xcdbString = log.getOperatorName();
				} else {

				}
			}
			visaModel.setDeptName(xcdbString + eycString);
		}

		if (StringUtils.isNotNull(visaModel.getVisAudit())) {
			visaModel.setStatus(Global.NUMERICAL_TWO + "");
			result = visaDao.update(visaModel);
		} else {
			result = visaDao.update(visaModel);
			return HttpResult.error("审批未结束！");
		}
		HttpResult httpResult = new HttpResult();
		if (result > 0) {
			httpResult.setMsg("成功!");
		} else {
			httpResult.setMsg("失败!");
		}
		return httpResult;
	}

	@Transactional
	public HttpResult commitXY(VisaModel visaModel) {
		HttpResult httpResult = new HttpResult();

		HashMap<String, Object> hashMap = new HashMap<>();
		hashMap.put("casid", visaModel.getVisDockHi());
		SysUser sysUser = sysUserMapper.selectByCasName(hashMap);

		if (sysUser == null) {
			return HttpResult.error("该员工内部账号不存在，请和对接人联系");
		}
		int result = 0;
		// 推送oa
		if (StringUtils.isNullOrEmpty(visaModel.getOaFlowId())) {
			HttpResult oaResult = createXYVisaService.CreateContract(visaModel, visaModel.getVisDockHi());
			if (oaResult.getCode() != HttpStatus.SUCCESS_CODE) {
				// 强制手动事务回滚
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return HttpResult.error(oaResult.getMsg());
			}
			OaWorkFlowResult oaWorkFlowResult = (OaWorkFlowResult) oaResult.getData();
			visaModel.setOaFlowId(oaWorkFlowResult.getOaFlowId() + "");
		} else {
			HttpResult oaResult = createXYVisaService.submit(visaModel, visaModel.getVisDockHi());
			if (oaResult.getCode() != HttpStatus.SUCCESS_CODE) {
				// 强制手动事务回滚
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return HttpResult.error(oaResult.getMsg());
			}
		}

		visaModel.setStatus(Global.YES + "");
		visaModel.setVisDockId(sysUser.getUserid());
		visaModel.setVisDockName(sysUser.getUsername());

		result = visaDao.update(visaModel);

		if (result > 0) {
			httpResult.setMsg(visaModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(visaModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(visaModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	@Transactional
	public HttpResult commitSP(VisaModel visaModel) {
		HttpResult httpResult = new HttpResult();

		HashMap<String, Object> hashMap = new HashMap<>();
		hashMap.put("casid", visaModel.getVisDockHi());
		SysUser sysUser = sysUserMapper.selectByCasName(hashMap);

		if (sysUser == null) {
			return HttpResult.error("该员工内部账号不存在，请和对接人联系");
		}
		int result = 0;
		// 推送oa
		if (StringUtils.isNullOrEmpty(visaModel.getOaFlowId())) {
			HttpResult oaResult = createSPVisaService.CreateContract(visaModel, visaModel.getVisDockHi());
			if (oaResult.getCode() != HttpStatus.SUCCESS_CODE) {
				// 强制手动事务回滚
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return HttpResult.error(oaResult.getMsg());
			}
			OaWorkFlowResult oaWorkFlowResult = (OaWorkFlowResult) oaResult.getData();
			visaModel.setOaFlowId(oaWorkFlowResult.getOaFlowId() + "");
		} else {
			HttpResult oaResult = createSPVisaService.submit(visaModel, visaModel.getVisDockHi());
			if (oaResult.getCode() != HttpStatus.SUCCESS_CODE) {
				// 强制手动事务回滚
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return HttpResult.error(oaResult.getMsg());
			}
		}

		visaModel.setStatus(Global.YES + "");
		visaModel.setVisDockId(sysUser.getUserid());
		visaModel.setVisDockName(sysUser.getUsername());

		result = visaDao.update(visaModel);

		if (result > 0) {
			httpResult.setMsg(visaModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(visaModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(visaModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * 删除
	 *
	 * @param
	 * @return
	 */
	public HttpResult delete(String visId) {
		HttpResult httpResult = new HttpResult();
		if (!StringUtils.isNotNull(visId)) {
			return HttpResult.error("参数不能为空");
		}
		VisaModel model = visaDao.load(visId);
		if (!model.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("非待提交状态，不可删除！");
		}
		int result = visaDao.delete(visId);
		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	public void export(Map<String, Object> queryMap, HttpServletResponse response) {
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				queryMap.put("createId", sysUser.getUserid());
			}
		}
		List<VisaModel> list = visaDao.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), VisaModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}

	/**
	 * 导出
	 * 
	 * @param queryMap
	 * @param response
	 */
	public void exportXY(Map<String, Object> queryMap, HttpServletResponse response) {
		SupplyUserModel sysUser = SpringMvcUtils.getSupplyUser();
		queryMap.put("createId", sysUser.getUserId());
		List<VisaModel> list = visaDao.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), VisaModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}

	public void exportSP(Map<String, Object> queryMap, HttpServletResponse response) {
		SupplyUserModel sysUser = SpringMvcUtils.getSupplyUser();
		queryMap.put("createId", sysUser.getUserId());
		List<VisaModel> list = visaDao.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), VisaModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}
}
